import path from 'path'
import fs from 'fs'
import YAML from 'yaml'
import lodash from 'lodash'

/** 根据 ResourcesAssets 和 ResourcesLang 生成 hero Object
 *  根据fileName生成不同配置文件 hero.json hero.yaml hero.lua 
 */
function hero(fileName) {

    let hero = readAssets('hero'), langHero = readLang('lang_hero')
    let groups = readAssets('groups'), langGroups = readLang('lang_groups')
    let skill = readAssets('skill'), langSkill = readLang('lang_skill')
    let skillLevel = readAssets('skill_level'), langSkillLevel = readLang('lang_skill_level')
    let charData = readAssets('char_data'), langCharData = readLang('lang_char_data')
    let charVoice = readAssets('char_voice'), langCharVoice = readLang('lang_char_voice')
    let profession = readAssets('profession'), langProfession = readLang('lang_profession')
    let elementType = readAssets('element_type'), langElementType = readLang('lang_element_type')
    let weaponType = readAssets('weapon_type')
    let battleTag = readAssets('battle_tag')
    let talentRank = readAssets('talent_rank')
    let talentRune = readAssets('talent_rune'), langTalentRune = readLang('lang_talent_rune')
    let commonItem = readAssets('common_item'), langCommonItem = readLang('lang_common_item')
    let rarity = readAssets('rarity')
    let charVoiceWordsBattle = readAssets('char_voice_words_battle'), langCharVoiceWordsBattle = readLang('lang_char_voice_words_battle')
    let charVoiceWordsExplore = readAssets('char_voice_words_explore'), langCharVoiceWordsExplore = readLang('lang_char_voice_words_explore')
    let species = readAssets('species'), langSpecies = readLang('lang_species')

    let heroMap = hero.reduce((heroMap, hero, index) => {
        let heroCharData = getObjectById(charData, hero.id)
        if (hero.id == 199999) return heroMap//公共技能承载（不可用）
        heroMap[hero.id] = {
            ...hero,
            // id
            id: hero.id,
            englishName: hero.englishName,
            favor: hero.favor,
            cost: hero.cost,
            // 名称
            name: getValueById(langHero, hero.name),
            // 定位/职业
            position: {
                name: getValueById(langProfession, getValueById(profession, hero.position, 'id', 'name')),
                icon: getValueById(profession, hero.position, 'id', 'icon').split(','),
                desc: getValueById(langProfession, getValueById(profession, hero.position, 'id', 'desc')),
            },
            // 稀有度
            rarity: {
                ...getObjectById(rarity, hero.rarity),
                frameIcon: getValueById(rarity, hero.rarity, 'id', 'frameIcon').split(','),
            },
            // 属性
            element: {
                ...lodash.pick(getObjectById(elementType, hero.element), ['id', 'elementColor', 'skillElem']),
                name: getValueById(langElementType, getValueById(elementType, hero.element, 'id', 'name')),
                abbrName: getValueById(langElementType, getValueById(elementType, hero.element, 'id', 'abbrName')),
            },
            // 战斗定位
            battleTag: hero.battleTag.split('|').map(tagId => lodash.omit(getObjectById(battleTag, tagId), ['battle'])),
            // 武器
            weaponType: getObjectById(weaponType, hero.weaponType),
            // 技能
            skillSystem: hero.skillSystem.split('|').map(id => {
                let skillLevels = skillLevel.filter(skillItem => skillItem.skillId == id)
                return {
                    ...getObjectById(skill, id),
                    name: getValueById(langSkill, getValueById(skill, id, 'id', 'name')),
                    skillName: getValueById(langSkillLevel, skillLevels[0]?.name),
                    skillDescribe: getValueById(langSkillLevel, skillLevels[0]?.skillDescribe),
                    skillSpecialDesc: getValueById(langSkillLevel, skillLevels[0]?.skillSpecialDesc),
                    skillLevel: {
                        name: skillLevels?.[0]?.name.split('|').map(name => getValueById(langSkillLevel, name)),
                        golds: skillLevels.map(skillItem => skillItem.gold),
                        values: skillLevels.map(skillItem => skillItem.value.split('|').map(value => getValueById(langSkillLevel, value)))
                    }
                }
            }),
            // 星赐
            talent: talentRank.filter(rank => rank.heroId === hero.id).map(rank => {
                return rank.rankBreakthroughItem.split('|').map(item => {
                    let rune = getObjectById(talentRune, item)
                    let common = getObjectById(commonItem, rune.runeItem)
                    return {
                        ...lodash.omit(rune, ['runeItem', 'equipRuneThroughCoin', 'runeAttribute', 'runeSkill', 'isDrop']),
                        ...lodash.pick(common, ['icon']),
                        name: getValueById(langCommonItem, common.name),
                        desc: getValueById(langCommonItem, common.desc),
                        tag: getValueById(langCommonItem, common.tag),
                        typeName: getValueById(langCommonItem, common.typeName),
                        way1desc: getValueById(langCommonItem, common.way1desc),
                        way2desc: getValueById(langCommonItem, common.way2desc),
                        // way3desc: getValueById(langCommonItem, common.way3desc),
                        runeTypeName: getValueById(langTalentRune, rune.runeTypeName),
                        runeTypeEngName: getValueById(langTalentRune, rune.runeTypeEngName),

                    }
                })
            }),
            dec: getValueById(langHero, hero.dec),
            // 台词
            charData: {
                // 所属
                characterGroup: {
                    ...getObjectById(groups, heroCharData.characterGroup),
                    name: getValueById(langGroups, getValueById(groups, heroCharData.characterGroup, 'id', 'name')),
                    icon: getValueById(groups, heroCharData.characterGroup, 'id', 'icon').split(',')
                },
                // 种族
                characterRace: {
                    id: heroCharData.characterRace,
                    name: getValueById(langSpecies, getValueById(species, heroCharData.characterRace, 'id', 'name')),
                },
                cvName: getValueById(langCharData, heroCharData?.cvName),
                cv_chs: getValueById(langCharData, heroCharData?.cv_chs),
                cv_jp: getValueById(langCharData, heroCharData?.cv_jp),
                cv_en: getValueById(langCharData, heroCharData?.cv_en),
                cv_kr: getValueById(langCharData, heroCharData?.cv_kr),
                cv_cht: getValueById(langCharData, heroCharData?.cv_cht),
                // 角色简介
                introduction: getValueById(langCharData, heroCharData?.introduction),
                // 生日
                characterBirthday: getValueById(langCharData, heroCharData?.characterBirthday),
                // 台词
                characterVoice: heroCharData?.characterVoice?.split('|').map(voiceId => {
                    let heroCharVoice = getObjectById(charVoice, voiceId)
                    return {
                        audioEvent: heroCharVoice.audioEvent,
                        title: getValueById(langCharVoice, heroCharVoice.title),
                        text: getValueById(langCharVoice, heroCharVoice.text),
                    }
                }),
            },


            battle: Object.entries(getObjectById(charVoiceWordsBattle, hero.id)).reduce((battle, [key, langKey]) => {
                if (key == 'id') return battle
                battle[key] = getValueById(langCharVoiceWordsBattle, langKey)
                return battle
            }, {}),
            explore: Object.entries(getObjectById(charVoiceWordsExplore, hero.id)).reduce((explore, [key, langKey]) => {
                if (key == 'id') return explore
                explore[key] = getValueById(langCharVoiceWordsExplore, langKey)
                return explore
            }, {}),

            avatarTexture: hero.avatarTexture.split(',')
        }
        return heroMap
    }, {})
    writeFile(fileName, heroMap)
    return heroMap
}

/** 根据 ResourcesAssets 和 ResourcesLang 生成 pet Object
 *  根据fileName生成不同配置文件 pet.json pet.yaml pet.lua 
 */
function pet(fileName) {
    let pet = readAssets('pet'), langPet = readLang('lang_pet')
    let elementType = readAssets('element_type'), langElementType = readLang('lang_element_type')
    let battleTag = readAssets('battle_tag')
    let petRace = readAssets('pet_race')
    let skill = readAssets('skill'), langSkill = readLang('lang_skill')
    let skillLevel = readAssets('skill_level'), langSkillLevel = readLang('lang_skill_level')
    let petMap = pet.reduce((petMap, pet, index) => {
        if (pet.id == 500297 || pet.id == 500298 || pet.id == 500264) return petMap
        petMap[pet.id] = {
            ...pet,
            // 名称
            name: getValueById(langPet, pet.name),
            kiboBoxCardIcon: pet.kiboBoxCardIcon.split(','),
            // 属性
            element: pet.element.split('|').map((item) => {
                return {
                    ...getObjectById(elementType, item),
                    name: getValueById(langElementType, getValueById(elementType, item, 'id', 'name')),
                    abbrName: getValueById(langElementType, getValueById(elementType, item, 'id', 'abbrName')),
                }
            }),
            // 职业
            battleTag: getObjectById(battleTag, pet.battleTag),
            // 描述
            desc: getValueById(langPet, pet.desc),
            // 种族
            race: pet.race.split('|').map(raceId => getObjectById(petRace, raceId, 'ID', 'raceType')),
            // 战斗天赋
            breakSkillList: pet.breakSkillList.split('|').map(item => {
                let id = item.replace(/\d+#(\d+)(#\d+)?/, (_, id) => id)
                let level = skillLevel.filter(({ skillId }) => skillId == id).sort((a, b) => a.level - b.level)
                return {
                    ...getObjectById(skill, id),
                    level: level.map(({ id, skillDescribe }) => {
                        return {
                            id,
                            skillDescribe: getValueById(langSkillLevel, skillDescribe)
                        }
                    }),
                    name: getValueById(langSkill, getValueById(skill, id, 'id', 'name')),

                }
            }),
            skillList: pet.skillList.split('|').map(item => {
                let id = item.replace(/\d+#(\d+)(#\d+)?/, (_, id) => id)
                let level = skillLevel.filter(({ skillId }) => skillId == id).sort((a, b) => a.level - b.level)
                return {
                    ...getObjectById(skill, id),
                    level: level.map(({ id, skillDescribe }) => {
                        return {
                            id,
                            skillDescribe: getValueById(langSkillLevel, skillDescribe)
                        }
                    }),
                    name: getValueById(langSkill, getValueById(skill, id, 'id', 'name')),

                }
            }),
            signatureSkillList: pet.signatureSkillList.split('|').map(item => {
                let id = item.replace(/\d+#(\d+)(#\d+)?/, (_, id) => id)
                let level = skillLevel.filter(({ skillId }) => skillId == id).sort((a, b) => a.level - b.level)
                return {
                    ...getObjectById(skill, id),
                    level: level.map(({ id, skillDescribe }) => {
                        return {
                            id,
                            skillDescribe: getValueById(langSkillLevel, skillDescribe)
                        }
                    }),
                    name: getValueById(langSkill, getValueById(skill, id, 'id', 'name')),

                }
            }),
            // 家园公种
            // 特性
            // 掉落素材
            // 阶段
            // 身高
        }
        return petMap
    }, {})
    writeFile(fileName, petMap)
    return petMap
}


/**
 * 配置方法
 */
// 读取文件
const readAssets = (fileName) => JSON.parse(fs.readFileSync(path.join(process.cwd(), 'ResourcesAssets/Config/NewTable', fileName + '.json'))) || []
const readLang = (fileName) => JSON.parse(fs.readFileSync(path.join(process.cwd(), 'ResourcesLang/chs/Table', fileName + '.json'))) || []
// 从数组里根据id，返回value
const getValueById = (arr, id, idName = 'id', valueName = 'value') => id ? arr.find(item => item[idName] == id)?.[valueName] : undefined
const getObjectById = (arr, id, idName = 'id') => id ? arr.find(item => item[idName] == id) : undefined
// 生成文件
const writeFile = (fileName, data) => {

    const convertValue = (value) => {
        if (value === null) return 'nil';
        if (typeof value === 'string') return `"${value.replace(/"/g, '\\"')}"`;
        if (typeof value === 'number' || typeof value === 'boolean') return value.toString();
        if (Array.isArray(value)) {
            return `{${value.map(item => convertValue(item)).join(', ')}}`;
        }
        if (typeof value === 'object') {
            const entries = Object.entries(value)
                .map(([k, v]) => `${k} = ${convertValue(v)}`);
            return `{${entries.join(', ')}}`;
        }
        return 'nil';
    };

    // 如果filename结尾为yaml,则，
    if (fileName.endsWith('.yaml')) {
        fs.writeFileSync(path.join(process.cwd(), fileName), YAML.stringify(data), 'utf8')
    } else if (fileName.endsWith('.lua')) {
        // 创建lua文件夹
        fs.mkdirSync(path.join(process.cwd(), fileName.replace('.lua', '')), { recursive: true });
        Object.entries(data).forEach(([key, value]) => {
            let content = convertValue(value)
            content = content.replace(/UI\/[\w-_ ]+\/[\w-_ ]+\/tex/g, 'tex')
            fs.writeFileSync(path.join(process.cwd(), fileName.replace('.lua', ''), `${key}`), `local p = {}\n p.data=${content}\nreturn p`, 'utf8')
        });
    } else {
        fs.writeFileSync(path.join(process.cwd(), fileName), JSON.stringify(data), 'utf8')
    }



}
// 创建文件夹并复制文件
let icons = []
const copyFile = (filePath, includeName) => {
    fs.mkdirSync(path.join(process.cwd(), filePath), { recursive: true })
    icons.forEach(icon => {
        if (icon.includes(includeName)) {
            // 创建文件
            fs.writeFileSync(
                path.join(process.cwd(), filePath, icon),
                fs.readFileSync(path.join(process.cwd(), 'icon', icon)))
        }
    })
}




/**
 * 调用生成
 */

hero('hero.yaml')
// pet('pet.yaml')